import 'package:api/pages/provider/getX/demo/shop/shop_controller.dart';
import 'package:api/pages/provider/getX/demo/shop/shop_item_page.dart';
import 'package:api/pages/provider/getX/demo/shop/shop_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class ShopMainPage extends StatefulWidget {
  @override
  _ShopMainPageState createState() => _ShopMainPageState();
}

class _ShopMainPageState extends State<ShopMainPage>
    with SingleTickerProviderStateMixin {
  TabController _tabController;
  // 创建并注入 ShopController
  ShopController _shopController = Get.put(ShopController());
  @override
  void initState() {
    super.initState();
    // 网络请求获取分类数据
    _shopController.request();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder(builder: (ShopController controller) {
      // 获取数据
      List<ShopClassBean> classList = controller.classBeanList;
      if (classList.length == 0) {
        return Scaffold(
          appBar: AppBar(title: Text("商品页面")),
          body: Center(
            child: Text("加载中"),
          ),
        );
      }
      _tabController = new TabController(length: classList.length, vsync: this);
      // tab
      List<Tab> tabList = [];
      // 子页面
      List<Widget> itemList = [];
      classList.forEach((element) {
        // 顶部标签
        tabList.add(Tab(text: element.title));
        // 标签子页面
        itemList.add(ShopItemPage(element));
      });

      return Scaffold(
        backgroundColor: Color(0xfff6f6f6),
        appBar: AppBar(
          title: Text("provider学习"),
          bottom: buildTabBar(tabList),
        ),
        body: buildTabView(itemList),
        floatingActionButton: Stack(alignment: Alignment.center, children: [
          ClipOval(
            child: Container(
              color: Colors.blue,
              height: 44,
              width: 44,
            ),
          ),
          Positioned(
            child: GetBuilder(
                id: 'card',
                builder: (ShopController controller) {
                  return Text("${controller.cardList.length}",
                      style: TextStyle(color: Colors.white));
                }),
          ),
        ]),
      );
    });
  }

  buildTabBar(List<Tab> tabList) {
    return TabBar(
      isScrollable: true,
      controller: _tabController,
      tabs: tabList,
    );
  }

  buildTabView(List<Widget> itemList) {
    return TabBarView(
      controller: _tabController,
      children: itemList,
    );
  }
}
